package com.weilai.controller;

import com.weilai.controller.exceptionHandler.BusinessException;
import com.weilai.controller.exceptionHandler.Code;
import com.weilai.controller.exceptionHandler.SystemException;
import com.weilai.dao.ViewsDao;
import com.weilai.domain.*;
import com.weilai.service.*;
import com.weilai.util.UploadUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@Api(tags = "用户主页", description = "提供用户主页会用到的方法的接口")
@Controller
@RequestMapping("/userHomepage")
public class UserHomepageController {

    @Autowired
    private UserService userService;

    @Autowired
    private LikesService likesService;

    @Autowired
    private PostsService postsService;

    @Autowired
    private FollowersService followersService;

    @Autowired
    private VideosService videosService;

    @Autowired
    private ViewsService viewsService;

    @Autowired
    private BackgroundService backgroundService;
    @Autowired
    private ThoughtService thoughtService;

    @ApiOperation(value = "跳转个人主页，也是获取动态", notes = "在跳转的同时，传递用户对象")
    @ApiResponses({
            @ApiResponse(code = 200, message = "跳转成功")
    })
    //跳转个人主页
    @GetMapping
    public ModelAndView homepage(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        HttpSession session = request.getSession();

        try {
            // 检查用户是否登录
            int id = (int)session.getAttribute("userId");
            User user = (User)session.getAttribute("user");
            if (user == null) {
                throw new BusinessException(Code.PROJECT_ACCESS_DENIED, "请先登录");
            }
            mav.addObject("user", user);
            mav.addObject("backgroundUrl",backgroundService.getByUserId(id).getUrl());

            // 获取文章
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("posts", posts);
            mav.addObject("postsNum", posts.size());

            //视频数量
            List<Videos> videos = videosService.selectByUserId(id);
            mav.addObject("videosNum", videos.size());

            //点赞数量
            List<Likes> likes = likesService.getLikesByUserId(id);
            mav.addObject("likesNum", likes.size());

            //想法数量
            List<Thought> Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //粉丝数量
            mav.addObject("fansNum", user.getFollowerCount());

            //关注数量
            mav.addObject("followerNum", user.getSubscription());

            mav.setViewName("personCenterArticle");
            return mav;

        } catch (BusinessException e) {
            // 业务异常直接抛出，由全局异常处理器处理
            throw e;
        } catch (Exception e) {
            // 未知系统异常转换为SystemException
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "加载个人主页失败", e);
        }
    }

    @ApiOperation(value = "更改头像", notes = "")
    //更改头像
    @ResponseBody
    @PostMapping("/updateAvatar")
    public Map<String, Object> updateAvatar(@RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
        Map<String, Object> resultMap = new HashMap<>();
        HttpSession session = request.getSession();
        int id = (int) session.getAttribute("userId");

        try {
            // 参数校验
            if (file.isEmpty()) {
                throw new BusinessException(
                        Code.PROJECT_VALIDATE_ERROR,
                        "请上传头像"
                );
            }

            // 文件类型校验
            String[] allowedTypes = {"image/jpeg", "image/png", "application/pdf"};
            if (!Arrays.asList(allowedTypes).contains(file.getContentType())) {
                throw new BusinessException(
                        Code.PROJECT_VALIDATE_ERROR,
                        "上传失败：仅支持 JPG/PNG/PDF 文件"
                );
            }

            // 文件大小校验
            if (file.getSize() > 5 * 1024 * 1024) {
                throw new BusinessException(
                        Code.PROJECT_VALIDATE_ERROR,
                        "图片大小不能超过5MB"
                );
            }

            User user = userService.getUserById(id);
            if (user == null) {
                throw new BusinessException(
                        Code.PROJECT_DATA_NOT_FOUND,
                        "用户不存在"
                );
            }

            // 上传头像
            String fileName = UploadUtil.upload(file);

            // 更改头像路径
            user.setAvatar(fileName);
            userService.updateUser(user);

            resultMap.put("success", true);
            resultMap.put("message", "上传成功");
            resultMap.put("url", fileName);
            resultMap.put("redirectUrl", "/personCenterArticle");
        } catch (BusinessException e) {
            throw e;
        } catch (IOException e) {
            throw new SystemException(
                    Code.SYSTEM_DB_ERROR,
                    "头像上传失败",
                    e
            );
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_UNKNOWN_ERROR, "系统异常，请稍后重试", e);
        }

        return resultMap;
    }

    @ApiOperation(value = "更改背景", notes = "")
    //更改背景
    @ResponseBody
    @PostMapping("/updateBackground")
    public Map<String, Object> updateBackground(@RequestParam MultipartFile file, HttpServletRequest request) throws IOException {
        Map<String, Object> resultMap = new HashMap<>();
        HttpSession session = request.getSession();
        int id = (int) session.getAttribute("userId");
        User user = userService.getUserById(id);

        if (user == null) {
            throw new BusinessException(
                    Code.PROJECT_DATA_NOT_FOUND,
                    "用户不存在"
            );
        }

        backgroundService.updateBackground(user.getId(), file);

        Background background = backgroundService.getByUserId(user.getId());

        resultMap.put("success", true);
        resultMap.put("message", "上传成功");
        resultMap.put("url", background.getUrl());
        resultMap.put("redirectUrl", "/personCenterArticle");

        return resultMap;
    }

    @ApiOperation(value = "获取点赞的帖子的方法", notes = "快捷访问点赞的帖子，会传递帖子集合、点赞帖子数量")
    @ApiResponses({
            @ApiResponse(code = 200, message = "获取成功")
    })
    //获取点赞的帖子...
    @GetMapping("/likes")
    public ModelAndView likes(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        HttpSession session = request.getSession();
        int id = (int) session.getAttribute("userId");
        User user = (User) session.getAttribute("user");

        try {
            // 获取点赞的帖子
            List<Likes> likes = likesService.getLikesByUserId(id);
            List<Posts> likePosts = new ArrayList<>();
            for (Likes like : likes) {
                try {
                    Posts post = postsService.selectById(like.getPostId());
                    if (post != null) {
                        likePosts.add(post);
                    }
                } catch (Exception e) {
                    throw new SystemException(Code.SYSTEM_DB_ERROR, "获取点赞数据失败", e);
                }
            }
            List<User> likesUsers = new ArrayList<>();
            for (Posts likePost : likePosts) {
                User u=userService.getUserById(likePost.getUserId());
                u.setPassword("****");
                likesUsers.add(u);
            }
            mav.addObject("user", user);
            mav.addObject("likesUsers", likesUsers);
            mav.addObject("likePosts", likePosts);
            mav.addObject("likesNum", likePosts.size());

            //文章数量
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("postsNum", posts.size());

            //视频数量
            List<Videos> videos = videosService.selectByUserId(id);
            mav.addObject("videosNum", videos.size());

            //想法数量
            List<Thought> Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //粉丝数量
            mav.addObject("fansNum", user.getFollowerCount());

            //关注数量
            mav.addObject("followerNum", user.getSubscription());

            mav.setViewName("personCenterLike");
        } catch (Exception e) {
            throw new SystemException(
                    Code.SYSTEM_DB_ERROR,
                    "获取点赞帖子失败",
                    e
            );
        }
        return mav;
    }

    @ApiOperation(value = "获取视频", notes = "")
    //获取视频
    @GetMapping("/videos")
    public ModelAndView videos(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        HttpSession session = request.getSession();
        int id = (int) session.getAttribute("userId");
        User user = (User) session.getAttribute("user");

        // 获取视频
        List<Videos> videos;
        try {
            videos = videosService.selectByUserId(id);
            mav.addObject("user", user);
            mav.addObject("videos", videos);
            mav.addObject("videosNum", videos.size());
            mav.setViewName("personCenterVideo");

            //文章数量
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("postsNum", posts.size());

            //点赞数量
            List<Likes> likes = likesService.getLikesByUserId(id);
            mav.addObject("likesNum", likes.size());

            //想法数量
            List<Thought> Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //粉丝数量
            mav.addObject("fansNum", user.getFollowerCount());

            //关注数量
            mav.addObject("followerNum", user.getSubscription());

        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "获取视频数据失败", e);
        }
        return mav;
    }

    @ApiOperation(value = "获取想法", notes = "")
    //获取想法
    @GetMapping("/views")
    public ModelAndView views(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        HttpSession session = request.getSession();
        int id = (int) session.getAttribute("userId");
        User user = (User) session.getAttribute("user");

        // 获取想法
        List<Thought> Thoughts;
        try {
            Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("user", user);
            mav.addObject("Thoughts", Thoughts);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //文章数量
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("postsNum", posts.size());

            //视频数量
            List<Videos> videos = videosService.selectByUserId(id);
            mav.addObject("videosNum", videos.size());

            //点赞数量
            List<Likes> likes = likesService.getLikesByUserId(id);
            mav.addObject("likesNum", likes.size());

            //粉丝数量
            mav.addObject("fansNum", user.getFollowerCount());

            //关注数量
            mav.addObject("followerNum", user.getSubscription());

            mav.setViewName("personCenterIdea");
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "获取想法数据失败", e);
        }
        return mav;
    }

    @ApiOperation(value = "获取关注者的方法", notes = "快捷访问关注者")
    //关注
    @GetMapping("/follower")
    public ModelAndView follower(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        HttpSession session = request.getSession();
        int id = (int) session.getAttribute("userId");
        User user = (User) session.getAttribute("user");

        // 获取关注
        try {
            List<User> follower = followersService.selectFollowingsById(id);
            for (User u : follower) {
                u.setPassword("****");
            }
            mav.addObject("user", user);
            mav.addObject("follower", follower);
            mav.addObject("followersNum", follower.size());
            //文章数量
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("postsNum", posts.size());

            //视频数量
            List<Videos> videos = videosService.selectByUserId(id);
            mav.addObject("videosNum", videos.size());

            //点赞数量
            List<Likes> likes = likesService.getLikesByUserId(id);
            mav.addObject("likesNum", likes.size());

            //想法数量
            List<Thought> Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //粉丝数量
            mav.addObject("fansNum", user.getFollowerCount());

            mav.setViewName("personCenterFollower");
        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "获取关注数据失败", e);
        }
        return mav;
    }

    @ApiOperation(value = "获取粉丝的方法", notes = "快捷访问粉丝")
    //粉丝
    @GetMapping("/fans")
    public ModelAndView fans(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView();
        HttpSession session = request.getSession();
        int id = (int) session.getAttribute("userId");
        User user = (User) session.getAttribute("user");

        // 获取粉丝
        try {
            List<User> fans = followersService.selectFansById(id);
            int[] followEachOther = new int[fans.size()];
            int i=0;
            for (User u : fans) {
                u.setPassword("****");
                if(followersService.isFollowing(id, u.getId())){
                    followEachOther[i]=1;

                }
                else{
                    followEachOther[i]=0;
                }
                i++;
            }
            mav.addObject("user", user);
            mav.addObject("fans", fans);
            mav.addObject("fansNum", fans.size());
            mav.addObject("followEachOther",followEachOther);

            //文章数量
            List<Posts> posts = postsService.selectMyAllArticle(id);
            mav.addObject("postsNum", posts.size());

            //视频数量
            List<Videos> videos = videosService.selectByUserId(id);
            mav.addObject("videosNum", videos.size());

            //点赞数量
            List<Likes> likes = likesService.getLikesByUserId(id);
            mav.addObject("likesNum", likes.size());

            //想法数量
            List<Thought> Thoughts = thoughtService.selectByUserId(id);
            mav.addObject("ThoughtsNum", Thoughts.size());

            //关注数量
            mav.addObject("followerNum", user.getSubscription());

            mav.setViewName("personCenterFans");

        } catch (Exception e) {
            throw new SystemException(Code.SYSTEM_DB_ERROR, "获取关注数据失败", e);
        }
        return mav;
    }
}
